package org.glorylight.hacks.social.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.glorylight.hacks.social.model.User;
import org.glorylight.hacks.social.model.UserRole;
import org.glorylight.hacks.social.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserAuthenticationProvider implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserAuthenticationProvider.class);
	private static final String ROLE_PREFIX = "ROLE_";

	private UserService userService;

	public List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + role.toUpperCase()));
		}
		return authorities;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User domainUser = userService.findUserForCredential(username);
        if (domainUser == null)
                throw new UsernameNotFoundException("credetial can not be authenticate");
        //              if(domainUser.getPassword())
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
        List<String> roles = new ArrayList<String>();
        for (UserRole userRole : domainUser.getRoles()) {
                roles.add(userRole.getRole().getRole().toUpperCase());
        }
        log.info("password : {}", new Object[]{new String(ArrayUtils.toPrimitive(domainUser.getPassword()))});
        return new org.springframework.security.core.userdetails.User(domainUser.getEmailAddress(), 
        		new String(ArrayUtils.toPrimitive(domainUser.getPassword())), enabled, 
        		accountNonExpired, credentialsNonExpired, accountNonLocked, getGrantedAuthorities(roles));
	}

}
